<template>
  <div class="student-list-box">
    <div style="display:flex">
      <!-- <div>
        <el-button size="mini" type="success" @click="addFormAlert">单个添加</el-button>
      </div>-->
      <div class="search-Box">
        <div class="left-box">
          <div class="item">
            <div class="in-item">
              <span class="label" style>学生学号:</span>
              <el-input size="mini" placeholder="输入搜索学号" v-model="tempSearchParam.nid"></el-input>
            </div>
            <div class="in-item">
              <span class="label" style="margin-left:35px">所属班级:</span>
              <el-input size="mini" placeholder="输入搜索班级名称" v-model="tempSearchParam.class"></el-input>
            </div>
          </div>
          <div class="item">
            <div class="in-item">
              <span class="label" style>归属学年:</span>
              <el-input size="mini" placeholder="输入搜索学年" v-model="tempSearchParam.xn"></el-input>
            </div>
            <div class="in-item">
              <span class="label" style>所属专业:</span>
              <el-select
                size="mini"
                clearable
                v-model="specialyNumList.value"
                placeholder="请选择"
                @change="cOptionChange"
              >
                <el-option
                  v-for="item in specialyNumList.list"
                  :key="item._id"
                  :label="item.name"
                  :value="item._id"
                ></el-option>
              </el-select>
              <!-- <el-input size="mini" placeholder="输入搜索" v-model="tempSearchParam.specialty"></el-input> -->
            </div>
          </div>
        </div>
        <div class="right-box">
          <div class="item">
            <el-button
              style="margin-left:20px"
              size="mini"
              type="primary"
              icon="el-icon-search"
              @click="search"
            >搜索</el-button>
            <el-upload
              class="upload"
              ref="upload"
              action="notUse"
              :file-list="fileList"
              :auto-upload="false"
              :http-request="uploadFile"
              :before-upload="beforeUpload"
              accept=".xls, .xlsx"
              :limit="1"
            >
              <el-button slot="trigger" size="small" type="primary">导入学生列表</el-button>
              <el-button
                style="margin-left: 10px;"
                size="small"
                type="success"
                @click="submitUpload"
              >上传到服务器</el-button>
              <div slot="tip" class="el-upload__tip">
                <i style="font-style:normal;font-weight:bold">提示</i>:导入学生信息，只能上传xls/xlsx文件，且不超过2mb
              </div>
            </el-upload>
          </div>
        </div>
      </div>
    </div>
    <el-table :data="studentList" stripe style="width: 100%;height:600px">
      <el-table-column prop="nid" label="学号"></el-table-column>
      <el-table-column prop="class.name" label="所属班级"></el-table-column>
      <el-table-column prop="name" label="学生姓名"></el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="checkInfo(scope.$index, scope.row)">查看详细信息</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="foot-box">
      <div style="width:50%">
        <el-button type="success" @click="rufush">刷新</el-button>
      </div>
      <div style="width:50%">
        <el-pagination
          background
          :current-page="option.nowPage"
          layout="prev, pager, next"
          :page-size="option.size"
          :total="option.counts"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>

    <!-- <div :class="['formBg',isShow?'show':'']">
      <el-form class="form">
        <el-form-item>
          <p>
            <span class="title">学生信息填写</span>
          </p>
          <div style="width:800px;">
            <el-form-item label="姓名">
              <el-input v-model="studentInfo1.name"></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-select v-model="sexValue" filterable placeholder="请选择" @change="sexChange">
                <el-option v-for="item in ['男','女']" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="身份证号">
              <el-input v-model="studentInfo1.identity"></el-input>
            </el-form-item>
            <el-form-item label="籍贯">
              <el-input v-model="studentInfo1.nativeplace"></el-input>
            </el-form-item>
            <el-form-item label="班级">
              <el-select
                v-model="classNumList.value"
                filterable
                placeholder="请选择"
                @change="classNumListChange"
              >
                <el-option
                  v-for="item in classNumList.list"
                  :key="item._id"
                  :label="item.name"
                  :value="item._id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属专业">
              <el-input disabled v-model="specialyNumList.value"></el-input>
            </el-form-item>
            <el-form-item label="民族">
              <el-input v-model="studentInfo1.nation"></el-input>
            </el-form-item>
            <el-form-item label="来源地">
              <el-input v-model="studentInfo1.source"></el-input>
            </el-form-item>
            <el-form-item label="入学年份">
              <el-input disabled v-model="studentInfo1.xn"></el-input>
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input v-model="studentInfo1.phone"></el-input>
            </el-form-item>
            <el-form-item label="家庭地址">
              <el-input v-model="studentInfo1.address"></el-input>
            </el-form-item>
            <el-form-item style="display:flex;align-item:center;justify-content:center">
              <el-button
                style="width:100px;margin-right:30px;margin-top:30px"
                type="primary"
                @click="addOneSubmit"
              >添加</el-button>
              <el-button style="width:100px" @click="close">取消</el-button>
            </el-form-item>
          </div>
        </el-form-item>
      </el-form>
    </div>-->
  </div>
</template>

<script>
import XLSX from "xlsx";
import { handlePageList, readExcel, handleMessage } from "../../plugins";
export default {
  data() {
    return {
      tempSearchParam: {},
      searchParam: {},
      option: { size: 10, counts: 0, nowPage: 1 },
      studentList: [],
      isShow: false,
      studentInfo1: {},
      editForm: {},
      fileList: [],
      specialyNumList: {
        value: "",
        list: []
      },
      batchPushList: [],
      classNumList: {
        value: "",
        list: []
      },
      choseYear: "",
      sexValue: "",
      isSearch: false
    };
  },
  methods: {
    cClear() {
      this.tempSearchParam.specialty = "";
    },
    cOptionChange(e) {
      this.tempSearchParam.specialty = e;
    },
    rufush() {
      this.option.nowPage = 1;
      this.searchParam.page = 1;
      this.isSearch = false;
      this.getStudentList();
      this.searchParam.class = "";
      this.searchParam.specialty = "";
      this.searchParam.year = "";
      this.tempSearchParam = {};
      this.specialyNumList.value = "";
    },
    async search() {
      this.option.nowPage = 1;
      this.isSearch = true;
      this.searchParam.page = 1;
      this.searchParam.xn = this.tempSearchParam.xn;
      this.searchParam.nid = this.tempSearchParam.nid;
      let classres = await this.$http.get(
        "rest/Class?name=" + this.tempSearchParam.class
      );
      if (classres.data.length == 1) {
        this.searchParam.class = classres.data[0]._id;
      } else {
        this.searchParam.class=''
        // if (
        //   this.tempSearchParam.xn ||
        //   this.tempSearchParam.specialty ||
        //   this.tempSearchParam.nid
        // ) {
        //   this.searchParam.class = "";
        // } else {
        //   this.searchParam.class = "error";
        // }
      }
      this.searchParam.specialty = this.tempSearchParam.specialty;
      console.log(this.searchParam.specialty);
      handlePageList(this, "searchList/Student", "studentList");
    },
    async uploadFile() {
      //这里发送增加请求，增加多数，后端要写个接口
      // TODO:这里添加请求，发送过去的数据就是json格式的batchPushList
      console.log(this.batchPushList);
      const loading = this.$loading({
        lock: true,
        text: "正在上传数据中，请稍等~",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let res = await this.$http.post(
        "insertRest/insertMore/Student",
        this.batchPushList
      );
      loading.close();
      if (res.data.success) {
        this.$message.success(res.data.message);
      } else {
        this.$message.error(res.data.message);
      }
      this.getStudentList();
      this.fileList = [];
    },
    beforeUpload(file) {
      let _this = this;
      //使返回的值变成Promise对象，如果校验不通过，则reject，校验通过，则resolve
      return new Promise(function(resolve, reject) {
        readExcel(_this, file, XLSX, "student").then(
          res => {
            const isLt2M = file.size / 1024 / 1204 < 2;
            if (!isLt2M) {
              _this.$message.error("文件大小不能超过2M！");
            }
            if (res && isLt2M) resolve(true);
            reject(false);
          },
          error => {
            //此处为reject返回时候
            _this.$message.error(error);
            reject(false);
          }
        );
      });
    },
    close() {
      this.studentInfo1 = {};
      this.isShow = false;
      this.classNumList.value = "";
      this.specialyNumList.value = "";
      this.sexValue = "";
    },

    checkInfo(index, row) {
      this.$router.push(`/manager/studentEdit/${row._id}`);
    },
    handleDelete(index, row) {
      this.$confirm(`是否确定要删除 "${row.name}"`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        const res = await this.$http.delete(`rest/Student/${row._id}`);
        this.$message({
          type: "success",
          message: "删除成功!"
        });
         if (this.isSearch) {
          handlePageList(this, "searchList/Student", "studentList");
        } else {
          this.getStudentList();
        }
        
      });
    },
    submitUpload() {
      this.$prompt("请输入导入学生信息所属学年", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          this.choseYear = value;
          this.getClassNumList();
        })
        .catch(() => {});
    },
    handleCurrentChange(e) {
      this.option.nowPage = e;
      this.searchParam.page = e;
      if (this.isSearch) {
        handlePageList(this, "searchList/Student", "studentList");
      } else {
        this.getStudentList();
      }
    },
    getStudentList() {
      return new Promise((re, rj) => {
        this.$http
          .get("list/Student", { params: this.searchParam })
          .then(res => {
            if (res.data.success) {
              this.studentList = res.data.list;
              this.option.counts = res.data.counts;
            } else {
              this.$message.error(res.data.message);
            }
            re && re();
          });
      });
    },
    getSpecialyNumList() {
      return new Promise((re, rj) => {
        this.$http.get("SpecialyNumList").then(res => {
          if (res.data.success) {
            this.specialyNumList.list = res.data.list;
          } else {
            this.$message.error(res.data.message);
          }
          re && re();
        });
      });
    },
    getClassNumList() {
      return new Promise((re, rj) => {
        this.$http
          .get("ClassNumList", {
            params: {
              year: this.choseYear.toString()
            }
          })
          .then(res => {
            if (res.data.success) {
              this.classNumList.list = res.data.list;
              if (!this.isShow) {
                this.$refs.upload.submit();
              }
            } else {
              this.$message.error(res.message);
            }
            re && re();
          });
      });
    },
    sexChange(e) {
      this.studentInfo1.sex = e;
    },
    classNumListChange(e) {
      this.studentInfo1.class = e;
      for (let i = 0; i < this.classNumList.list.length; i++) {
        let item = this.classNumList.list[i];
        if (item._id == e) {
          for (let z = 0; z < this.specialyNumList.list.length; z++) {
            let inItem = this.specialyNumList.list[z];
            if (item.superior == inItem._id) {
              this.studentInfo1.specialty = item.superior;
              this.specialyNumList.value = inItem.name;
            }
          }
        }
      }
    },
    // specialyNumListChange(e) {
    //   this.studentInfo1.specialty = e;
    // },
    onShow() {
      const loading = this.$loading({
        lock: true,
        text: "正在加载数据中，请稍等~",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      Promise.all([this.getSpecialyNumList(), this.getStudentList()])
        .then(res => {
          this.$nextTick(() => {
            loading.close();
          });
        })
        .catch(() => {
          this.$nextTick(() => {
            loading.close();
          });
        });
    }
    // addFormAlert() {
    //   this.$prompt("请输入添加学生所属学年", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消"
    //   })
    //     .then(({ value }) => {
    //       this.choseYear = value;
    //       this.studentInfo1.xn = value;
    //       const loading = this.$loading({
    //         lock: true,
    //         text: "正在加载数据中，请稍等~",
    //         spinner: "el-icon-loading",
    //         background: "rgba(0, 0, 0, 0.7)"
    //       });
    //       Promise.all([this.getClassNumList()])
    //         .then(() => {
    //           loading.close();
    //           this.isShow = true;
    //         })
    //         .catch(() => {});
    //     })
    //     .catch(() => {});
    // },
  },
  // async addOneSubmit() {
  //     if (!this.studentInfo1.name) {
  //       this.$message.error("请填写姓名！");
  //       return;
  //     }
  //     if (!this.studentInfo1.sex) {
  //       this.$message.error("请选择性别！");
  //       return;
  //     }
  //     if (!this.studentInfo1.identity) {
  //       this.$message.error("请填写身份证");
  //       return;
  //     }
  //     if (!this.studentInfo1.class) {
  //       this.$message.error("请选择班级！");
  //       return;
  //     }
  //     if (!this.studentInfo1.specialty) {
  //       this.$message.error("请选择专业");
  //       return;
  //     }
  //     if (!this.studentInfo1.phone) {
  //       this.$message.error("请填写手机号！");
  //       return;
  //     }
  //     if (!this.studentInfo1.address) {
  //       this.$message.error("请填写家庭住址！");
  //       return;
  //     }
  //     if (!this.studentInfo1.nativeplace) {
  //       this.$message.error("请填写籍贯！");
  //       return;
  //     }
  //     if (!this.studentInfo1.source) {
  //       this.$message.error("请填写来源地！");
  //       return;
  //     }
  //     if (!this.studentInfo1.nation) {
  //       this.$message.error("请填写民族！");
  //       return;
  //     }
  //     let res = await this.$http.post("Student/one", this.studentInfo1);
  //     handleMessage(this, res.data);
  //     this.close();
  //     this.getStudentList();
  //   },
  created() {
    this.onShow();
  }
};
</script>

<style scoped>
.el-form-item {
  display: inline-flex;
  margin-right: 10px;
}
.formBg {
  position: absolute;
  z-index: 100;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  justify-content: center;
  align-items: center;
  display: none;
}
.show {
  display: flex;
}
.form {
  background: #ffffff;
  border-radius: 5px;
  padding: 20px;
  padding-bottom: 8px;
  padding-top: 0;
}
.form .title {
  color: gray;
  border-bottom: 1px solid orange;
}
/* .upload {
  margin-left: 22px;
} */
.upload {
  margin-left: 50px;
}
.search-Box {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  width: 100%;
  /* margin-left: 100px; */
  justify-content: space-between;
}
.left-box {
  width: 50%;
}
.right-box {
  width: 50%;
}
.search-Box .item {
  margin-top: 20px;
  display: flex;
  align-items: center;
}
.search-Box .item:nth-child(1) {
  margin-top: 0;
}
.search-Box .in-item {
  display: flex;
  align-items: center;
}

.search-Box .in-item {
  margin-left: 50px;
}
.search-Box .in-item:nth-child(1) {
  margin: 0;
}
.in-item .label {
  width: 100px;
  font-size: 14px;
  text-align: right;
  margin-right: 10px;
}
.foot-box {
  display: flex;
  margin-top: 20px;
  align-items: flex-end;
  padding: 0 50px;
  padding-right: 80px;
  justify-content: space-between;
}
</style>